<template>
  <div class="layout">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-container">
        <!-- 左侧：系统标题 -->
        <div class="header-left">
          <i class="el-icon-menu"></i>
          <h1 class="system-title">焊接学习平台</h1>
        </div>

        <!-- 中间：导航菜单 -->
        <div class="header-center">
          <el-menu 
            :default-active="$route.path" 
            mode="horizontal" 
            router
            background-color="transparent"
            text-color="#fff"
            active-text-color="#ffd04b"
          >
            <el-menu-item index="/home">
              <i class="el-icon-s-home"></i>
              <span>首页</span>
            </el-menu-item>
            <el-menu-item index="/courses">
              <i class="el-icon-notebook-2"></i>
              <span>我的课程</span>
            </el-menu-item>
            <el-menu-item index="/training">
              <i class="el-icon-data-analysis"></i>
              <span>实训成绩</span>
            </el-menu-item>
            <el-menu-item index="/profile">
              <i class="el-icon-user"></i>
              <span>个人信息</span>
            </el-menu-item>
          </el-menu>
        </div>

        <!-- 右侧：用户信息 -->
        <div class="header-right">
          <!-- 用户下拉菜单 -->
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar 
                size="small" 
                :src="userAvatar"
                @error="handleAvatarError"
              >
                <i class="el-icon-user-solid"></i>
              </el-avatar>
              <span class="username">{{ username }}</span>
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="profile">
                <i class="el-icon-user"></i> 个人信息
              </el-dropdown-item>
              <el-dropdown-item command="logout" divided>
                <i class="el-icon-switch-button"></i> 退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="main-content">
      <div class="content-container">
        <router-view />
      </div>
    </main>

    <!-- 底部 -->
    <footer class="footer">
      <div class="footer-container">
        <p>&copy; 2024 焊接学习平台. All rights reserved.</p>
      </div>
    </footer>
  </div>
</template>

<script>
export default {
  name: 'Layout',
  data() {
    return {
      userInfo: {
        name: '学生',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
    }
  },
  computed: {
    username() {
      return this.userInfo.name || '学生'
    },
    userAvatar() {
      return this.userInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  },
  mounted() {
    // 从localStorage加载用户信息
    this.loadUserInfo()
    // 监听用户信息更新事件
    window.addEventListener('userInfoUpdated', this.loadUserInfo)
  },
  beforeDestroy() {
    window.removeEventListener('userInfoUpdated', this.loadUserInfo)
  },
  methods: {
    // 从环境变量获取基础URL
    getBaseUrl() {
      // 优先使用 VUE_APP_BASE_URL
      if (process.env.VUE_APP_BASE_URL) {
        return process.env.VUE_APP_BASE_URL.replace(/\/$/, '')
      }
      
      // 从 VUE_APP_BASE_API 中提取域名
      if (process.env.VUE_APP_BASE_API) {
        const baseApi = process.env.VUE_APP_BASE_API
        if (baseApi.startsWith('http://') || baseApi.startsWith('https://')) {
          return baseApi.replace(/\/api.*$/, '').replace(/\/$/, '')
        }
      }
      
      return ''
    },
    
    // 处理头像URL：将相对路径转换为完整URL
    processAvatarUrl(avatar) {
      if (!avatar || avatar === '') {
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
      
      // Base64格式，直接返回
      if (avatar.startsWith('data:image/')) {
        return avatar
      }
      
      // 已经是完整URL，添加时间戳后返回
      if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
        const timestamp = Date.now()
        return avatar + (avatar.includes('?') ? '&' : '?') + '_t=' + timestamp
      }
      
      // 相对路径，需要转换为完整URL
      const baseUrl = this.getBaseUrl()
      if (baseUrl) {
        const fullUrl = baseUrl + (avatar.startsWith('/') ? '' : '/') + avatar
        // 添加时间戳
        return fullUrl + (fullUrl.includes('?') ? '&' : '?') + '_t=' + Date.now()
      } else {
        return 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
    },
    
    async loadUserInfo() {
      // 先尝试从localStorage加载
      const savedUserInfo = localStorage.getItem('userInfo')
      if (savedUserInfo) {
        try {
          const userInfo = JSON.parse(savedUserInfo)
          const avatar = this.processAvatarUrl(userInfo.avatar || '')
          
          // 使用Vue.set更新对象属性，确保响应式更新
          this.$set(this.userInfo, 'name', userInfo.name || '学生')
          this.$set(this.userInfo, 'avatar', avatar)
        } catch (e) {
        }
      }
      
      // 如果localStorage中没有用户信息，从API获取
      if (!savedUserInfo) {
        try {
          const res = await this.$api.profile.getProfile()
          if (res) {
            const avatar = this.processAvatarUrl(res.avatar || '')
            
            // 使用Vue.set更新对象属性，确保响应式更新
            this.$set(this.userInfo, 'name', res.name || '学生')
            this.$set(this.userInfo, 'avatar', avatar)
            
            // 保存到localStorage供后续使用（保存原始URL）
            localStorage.setItem('userInfo', JSON.stringify({
              name: res.name,
              username: res.username,
              phone: res.phone,
              avatar: res.avatar || '', // 保存原始URL
              id_card: res.id_card
            }))
          }
        } catch (error) {
          // API获取失败，使用默认值
          this.$set(this.userInfo, 'name', '学生')
          this.$set(this.userInfo, 'avatar', 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
        }
      }
    },
    handleAvatarError(e) {
      // 头像加载失败时使用默认头像
      this.$set(this.userInfo, 'avatar', 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
    },
    handleCommand(command) {
      if (command === 'profile') {
        // 确保路由正确跳转
        if (this.$route.path !== '/profile') {
          this.$router.push('/profile').catch(err => {
          })
        }
      } else if (command === 'logout') {
        this.$confirm('确定要退出登录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          localStorage.removeItem('student_token')
          localStorage.removeItem('userInfo')
          this.$message.success('退出登录成功')
          this.$router.push('/login')
        }).catch(() => {})
      }
    }
  }
}
</script>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 0 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

/* 左侧标题 */
.header-left {
  display: flex;
  align-items: center;
  color: #fff;
  min-width: 200px;
}

.header-left .el-icon-menu {
  font-size: 24px;
  margin-right: 12px;
}

.system-title {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  white-space: nowrap;
}

/* 中间导航菜单 */
.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
}

.header-center >>> .el-menu {
  border: none;
}

.header-center >>> .el-menu-item {
  border: none;
  height: 60px;
  line-height: 60px;
  padding: 0 20px;
  font-size: 15px;
}

.header-center >>> .el-menu-item i {
  margin-right: 5px;
  font-size: 16px;
}

.header-center >>> .el-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.header-center >>> .el-menu-item.is-active {
  background-color: rgba(255, 255, 255, 0.15) !important;
  border-bottom: 2px solid #ffd04b;
}

/* 右侧用户信息 */
.header-right {
  min-width: 200px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.user-info {
  display: flex;
  align-items: center;
  color: #fff;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  margin: 0 8px 0 10px;
  font-size: 14px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  background-color: #f5f7fa;
  padding: 30px 0;
}

.content-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 0 30px;
}

/* 底部 */
.footer {
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  padding: 20px 0;
  margin-top: auto;
}

.footer-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 0 30px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    padding: 0 15px;
    height: auto;
    flex-wrap: wrap;
  }

  .header-left {
    width: 100%;
    justify-content: center;
    padding: 10px 0;
  }

  .header-center {
    width: 100%;
    order: 3;
  }

  .header-center >>> .el-menu {
    display: flex;
    justify-content: space-around;
  }

  .header-center >>> .el-menu-item {
    padding: 0 10px;
    font-size: 13px;
  }

  .header-center >>> .el-menu-item span {
    display: none;
  }

  .header-right {
    width: 100%;
    justify-content: center;
    padding: 10px 0;
  }

  .content-container {
    padding: 0 15px;
  }
}
</style>
